package org.zcl.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Package org.zcl.utils
 * @PROJECT_NAME: canal
 * @DESCRIPTION:
 * @USER: zhuchenglin
 * @DATE: 2022/3/31 16:52
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 删除key
     *
     * @param key
     */
    public boolean delete(String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 设置指定 key 的值
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        set(key, value,null);
    }

    /**
     * 设置redis的key-value，带过期时间
     */
    public void set(String key, String value, Long timeOut) {
        redisTemplate.opsForValue().set(key, value);
        if (timeOut != null) {
            redisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
        }
    }


    /**
     * 获取指定 key 的值
     * @param key
     * @return
     */
    public String get(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }
}
